<?php

App::uses('AppController', 'Controller');

/**
 * Projects Controller
 *
 */
class ProjectsController extends AppController {

    /**
     * Scaffold
     *
     * @var mixed
     */
    public $scaffold;
    public $uses = array('Project', 'ProjectDetail', 'ProjectType', 'Property', 'PropertyType', 'Province', 'Preference', 'Image', 'ProjectPreference');

    public function index() {
        $this->layout = "default_project";
        $projectTypeId =0;
        $propertyId=0;
        $propertyTypeId=0;
        $amphursId=0;
        $search=false;
        if(isset($this->request['url']['projectTypeId']) && is_numeric($this->request['url']['projectTypeId'])){
            $projectTypeId = $this->request['url']['projectTypeId'];
        }
        if(isset($this->request['url']['propertyId']) && is_numeric($this->request['url']['propertyId'])){
            $propertyId = $this->request['url']['propertyId'];
        }
        if(isset($this->request['url']['$propertyTypeId']) && is_numeric($this->request['url']['$propertyTypeId'])){
            $propertyTypeId = $this->request['url']['$propertyTypeId'];
        }
        if(isset($this->request['url']['amphursId']) && is_numeric($this->request['url']['amphursId'])){
            $amphursId = $this->request['url']['amphursId'];
        }
        if(isset($this->request['url']['search']) && is_bool($this->request['url']['search'])){
            $search = $this->request['url']['search'];            
        }
        //debug($propertyId);
        if($search==false){
            if($propertyId == RESIDENTIALL_ID){
                
                $this->setResidential($projectTypeId, $propertyId,$propertyTypeId);
            }else{
                $this->setCommercial($projectTypeId, $propertyId,$propertyTypeId);
            }
        }else{
            $this->setFromSearch($projectTypeId, $propertyId, $propertyTypeId, $amphursId);
        }
        
        $this->set('province', $this->Province->listOption($this->Session->read('Config.language')));
        $this->set('properties', $this->PropertyType->listOptionToDropdown());
        //$this->set('lists', $this->Project->listAllGuest($propertyId,$projectTypeId));
    }
    
    private function setFromSearch($projectTypeId,$propertyId,$propertyTypeId,$amphursId){
        
    }
    
    private function setResidential($projectTypeId,$propertyId,$propertyTypeId){
        $latest = $this->Project->listAllDetail($projectTypeId, $propertyId,$propertyTypeId, LIMIT_PER_PAGE);
        $houseArr = $this->Project->listAllDetail($projectTypeId, $propertyId, 10, LIMIT_PER_PAGE);
        $condoArr = $this->Project->listAllDetail($projectTypeId, $propertyId, 1, LIMIT_PER_PAGE);
        $dataAll = array(
            array(
                'title' => 'Latest',
                'data' => $latest
            ),
            array(
                'title' => 'DETACHBD HOUSE',
                'data' => $houseArr
            ),
             array(
                'title' => 'CONDOMINIUM',
                'data' => $condoArr
            )
        );
        //debug($dataAll);
        $this->set('dataAll', $dataAll);
        
    }
    
    private function setCommercial($projectTypeId,$propertyId,$propertyTypeId){
        
    }

    public function resale($propertyId = NULL, $propertyTypeId = NULL) {
        $this->set('newArr', $this->Project->listAllDetail(2, $propertyId, $propertyTypeId, LIMIT_PER_PAGE));
        $this->set('houseArr', $this->Project->listAllDetail(2, $propertyId, 10, LIMIT_PER_PAGE));
        $this->set('condoArr', $this->Project->listAllDetail(2, $propertyId, 1, LIMIT_PER_PAGE));
    }

    public function newProject($propertyId = NULL, $propertyTypeId = NULL) {
        $latest = $this->Project->listAllDetail(1, $propertyId, $propertyTypeId, LIMIT_PER_PAGE);
        $this->set('newArr', $latest);
        $this->set('houseArr', $this->Project->listAllDetail(1, $propertyId, 10, LIMIT_PER_PAGE));
        $this->set('condoArr', $this->Project->listAllDetail(1, $propertyId, 1, LIMIT_PER_PAGE));
       
    }

    public function type($projectTypeId = NULL, $propertyId = NULL, $propertyTypeId = NULL) {
        $this->set('newArr', $this->Project->listAllDetail($projectTypeId, $propertyId, $propertyTypeId));
    }

    public function listAll($propertyId = NULL,$projectTypeId=NULL) {
        $pData = $this->Property->getDetail($propertyId);
        $this->set('lists', $this->Project->listAllAdmin($propertyId,$projectTypeId));
        $this->set('propertyName', $pData['Property']['name_eng']);
        $this->set('title',($projectTypeId==TYPE_NEW?'New ':'Resale ').$pData['Property']['name_eng'].' Project');
        $this->set('propertyId', $propertyId);
        $this->set('projectTypeId',$projectTypeId);
    }

    public function add($propertyId = NULL,$projectTypeId=NULL) {
        if ($this->request->is('post')) {
            $this->request->data['Project']['create_by'] = $this->Session->read('User.username');
            $this->Project->set($this->request->data['Project']);
            $this->ProjectDetail->set($this->request->data['ProjectDetail']);

            if ($this->Project->validates()) {
                if ($this->ProjectDetail->validates()) {
                    $this->Project->save();
                    $projectId = $this->Project->getLastInsertID();
                    $webLang = Configure::read('WEB_LANG');
                    for ($i = 0; $i < sizeof($webLang); $i++) {
                        $this->request->data['ProjectDetail']['project_id'] = $projectId;
                        $this->request->data['ProjectDetail']['language'] = $webLang[$i];
                        $this->ProjectDetail->create();
                        $this->ProjectDetail->set($this->request->data['ProjectDetail']);
                        $this->ProjectDetail->save();
                    }
//                    $validator = $this->Project->validator();
//                    unset($validator['code']['duplicate']);
//                    $webLang = Configure::read('WEB_LANG');

                    $this->Session->setFlash('Add Success!! You can edit to others language.');
                    $this->redirect('/Projects/edit/' . $projectId);
                }
            }
        }
        $pData = $this->Property->getDetail($propertyId);
        $this->set('propertyName', $pData['Property']['name_eng']);
        
        $this->set('propertyId', $propertyId);
        $this->set('projectTypeId', $projectTypeId==NULL?1:$projectId);
        $this->set('province', $this->Province->listOption());
        $this->set('projectTypes', $this->ProjectType->getProjectTypeOptions());
        $this->set('properties', $this->PropertyType->listOptionToDropdown($propertyId));
    }

    public function edit($id) {
        $this->Project->Behaviors->load('Containable');
        //$this->ProjectDetail->Behaviors->load('Containable');
        if (isset($this->request['url']['lang'])) {
            $language = strtolower($this->request['url']['lang']);
        } else {
            $language = ENG_LANG;
        }

        if ($this->request->is('put')) {
            //debug($this->request->data);
            $this->Project->set($this->request->data['Project']);
            $this->ProjectDetail->set($this->request->data['ProjectDetail']);
            if ($this->Project->validates()) {
                $this->Project->save();
            }
            if ($this->ProjectDetail->validates()) {
                $this->ProjectDetail->save();
                $this->Session->setFlash('Update Success!!');
            }
        }

        $rec = $this->Project->getProject($language, $id);
        $this->Project->id = $id;

        $this->data = array('Project' => $rec['Project'], 'ProjectDetail' => $rec['ProjectDetail'][0]);
        //debug($this->data);
        $this->set('lang', $language);
        //$this->set('projectCode', $code);
        $this->set('projectId', $id);
        //$this->set('images', $this->Image->listImage($code));

        $this->set('province', $this->Province->listOption(Configure::read('Config.language')));
        $this->set('projectTypes', $this->ProjectType->getProjectTypeOptions());
        $this->set('properties', $this->PropertyType->listOptionToDropdown());
    }

    public function upImage($projectId) {
        if (isset($projectId) && $projectId != NULL) {
            if ($this->request->is('post')) {
                $valid_formats = array("jpg", "png", "JPG");
                $max_file_size = 1024 * 500; //100 kb
                $path = "uploads/"; // Upload directory
                $count = 0;
                $message = array();
                $imagesData = array();
                // Loop $_FILES to execute all files
                foreach ($_FILES['files']['name'] as $f => $name) {
                    //debug($_FILES["files"]["tmp_name"][$f]);
                    if ($_FILES['files']['error'][$f] == 4) {
                        continue; // Skip file if any error found
                    }
                    if ($_FILES['files']['error'][$f] == 0) {
                        if ($_FILES['files']['size'][$f] > $max_file_size) {
                            $message[] = "$name is too large!.";
                            continue; // Skip large files
                        } elseif (!in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats)) {
                            $message[] = "$name is not a valid format";
                            continue; // Skip invalid file formats
                        } else { // No error found! Move uploaded files 
                            $names = explode('.', $name);
                            $now = new DateTime();
                            $timeName = $now->format('YmdHis');
                            $newName = 'harrison_cnx_project_' . $projectId . '_' . $timeName . '_' . $f . '.' . $names[(sizeof($names) - 1)];
                            $path = 'uploads/projects/' . $newName;
                            $imagesData[] = array(
                                'name' => $newName,
                                'path' => $path,
                                'project_id' => $projectId
                            );
                            if (move_uploaded_file($_FILES["files"]["tmp_name"][$f], 'img/' . $path)) {
                                $count++; // Number of successfully uploaded files
                            }
                        }
                    }
                }
                $i = 0;
                foreach ($imagesData as $img) {
                    $this->Image->create();
                    $this->Image->set($img);
                    $this->Image->save();
                    if ($i == 0) {
                        $pData = $this->Project->find('first', array(
                            'conditions' => array(
                                'Project.id' => $projectId
                            )
                        ));
                        if ($pData['Project']['default_pic'] == NULL) {
                            //$imageId = $this->Image->getLastInsertID();
                        }
                        $i++;
                    }
                }
                $this->set('count', $count);
                $this->set('message', $message);

                $this->Session->delete('add_project');
                $this->Session->setFlash('All is Finish!!');
            }
            $images = $this->Image->listImage($projectId);
            $projects = $this->Project->getProject($this->Session->read('Config.language'), $projectId);
            $this->set('data', $projects);
            $this->set('images', $images);
            //debug($projects);
        } else {
            $this->redirect('/Projects/listAll');
        }
    }

    private function cloneProject($id, $targetLang) {
        $validator = $this->Project->validator();
        unset($validator['code']['duplicate']);

        $record = $this->Project->Find('first', array(
            'conditions' => array(
                'Project.id' => $id,
                'Project.language' => ENG_LANG
            )
        ));
        $data = array(
            'language' => $targetLang,
            'title' => $record['Project']['title'],
            'bedroom' => $record['Project']['bedroom'],
            'sub_title' => $record['Project']['sub_title'],
            'property_type_id' => $record['Project']['property_type_id'],
            'code' => $record['Project']['code'],
            'company' => $record['Project']['company'],
            'location' => $record['Project']['location'],
            'descriptions' => $record['Project']['descriptions'],
            'promotion' => $record['Project']['promotion'],
            'price_start' => $record['Project']['price_start'],
            'address' => $record['Project']['address'],
            'image_path' => $record['Project']['image_path'],
            'type_for' => $record['Project']['type_for'],
            'status' => $record['Project']['status'],
            'create_by' => 'sakorn.s'
        );

        $this->Project->saveAll($data);
        //debug($this->Project->invalidFields());
        return $this->Project->getLastInsertID();
    }

    public function delete($projectId = NULL,$propertyId=NULL) {
        if ($projectId != NULL) {
            $condition = array('Project.id' => $projectId);
            if ($this->Project->deleteAll($condition, false)) {
                //$condition = array('Image.code' => $code);
                //$this->Image->deleteAll($condition, false);
                //$conditionPro = array('ProjectPreference.project_code' => $code);
                //$this->ProjectPreference->deleteAll($conditionPro, false);

                $this->Session->setFlash('Remove Success!!');
                $this->redirect('/Projects/listAll/'.$propertyId);
            }
        }
    }

    public function view($id = NULL) {
        if ($id != NULL) {
            $images = $this->Image->listImage($id);
            $projects = $this->Project->getProject($this->Session->read('Config.language'), $id);
            $this->set('data', $projects);
            $this->set('images', $images);
        }
    }

    public function updateStatus($projectId, $status,$propertyId) {
        if ($status == 'yes') {
            $status = 'no';
        } else {
            $status = 'yes';
        }
        $data = $this->Project->find('first', array(
            'conditions' => array('Project.id' => $projectId)
        ));
        $this->Project->id = $data['Project']['id'];
        $this->Project->saveField('status', $status);
        $this->Session->setFlash('Update Success!!');
        $this->redirect('/Projects/listAll/'.$propertyId);
    }

    public function updatePath($imgID, $projectId) {
        $path = $this->Image->find('first', array(
            'conditions' => array('Image.id' => $imgID)
        ));
        $this->Project->id = $projectId;
        $this->Project->saveField('default_pic', $path['Image']['path']);
        $this->Session->setFlash('Update Success!!');
        $this->redirect('/Projects/upImage/' . $projectId);
    }

    public function search() {
        if ($this->request->is('post')) {
            debug($this->request->data);
            $type_for = $this->request->data['Project']['type_for'];
            $property_type_id = $this->request->data['Project']['property_type_id'];
            $location = $this->request->data['Project']['location'];
            $preferences = $this->request->data['Project']['preferences'];
            $bedroom = $this->request->data['Project']['bedroom'];
            if ($preferences == '') {
                $preferences = array();
            }
            if ($bedroom == '') {
                $bedroom = array();
            }

            $data = $this->Project->search($type_for, $property_type_id, $location, $preferences, $bedroom);
        } else {
            $data = $this->Project->listActive(0, $this->Session->read('Config.language') == 'tha' ? 'TH' : 'EN');
        }
        $bedroom = array(
            'Studio' => 'Studio',
            '1' => '1 Bedroom',
            '2' => '2 Bedrooms',
            '3' => '3 Bedrooms',
            '4' => '4 Bedrooms or more'
        );
        $this->set('bedrooms', $bedroom);
        $this->set('preferences', $this->Preference->listOption());
        $this->set('province', $this->Province->listOption($this->Session->read('Config.language')));
        $this->set('properties', $this->PropertyType->listOptionToDropdown());

        $this->set('lists', $data);
    }

}
